package com.example.smartmedicalsystem.config;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.*;
import java.io.IOException;
import java.util.Collection;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        String redirectUrl = "/login?error";
        for(GrantedAuthority authority : authorities){
            if(authority.getAuthority().equals("ROLE_ADMIN")){
                redirectUrl = "/admin/dashboard";
                break;
            } else if(authority.getAuthority().equals("ROLE_DOCTOR")){
                redirectUrl = "/doctor/dashboard";
                break;
            } else if(authority.getAuthority().equals("ROLE_PATIENT")){
                redirectUrl = "/patient/dashboard";
                break;
            }
        }
        response.sendRedirect(redirectUrl);
    }
}
